package com.twan.base.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.twan.base.R;
import com.twan.base.api.Api;
import com.twan.base.app.BaseActivity;
import com.twan.base.entity.LoginBean;
import com.twan.base.entity.MyFee;
import com.twan.base.entity.UploadImgBean;
import com.twan.base.network.ZyCallBack;
import com.twan.base.util.GlideUtils;
import com.twan.base.util.JsonUtil;
import com.twan.base.util.LogUtil;
import com.twan.base.util.MyUtil;
import com.twan.base.util.SPUtils;
import com.twan.base.util.ToastUtil;
import com.twan.base.widget.SelectHeadPopup;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.model.TakePhotoOptions;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.twan.base.app.Constants.SP_LOGIN_BEAN;

/**
 * @author Twan
 * @date 2019/4/24
 *
 * 业主报修
 */
public class MaintainActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.edt_desc) EditText edt_desc;
    @BindView(R.id.edit_name) EditText edit_name;
    @BindView(R.id.edit_phone) EditText edit_phone;
    @BindView(R.id.edit_house) EditText edit_house;
    @BindView(R.id.tv_bxtype) TextView tv_bxtype;

    @BindView(R.id.iv_1) ImageView iv_1;
    @BindView(R.id.iv_2) ImageView iv_2;
    @BindView(R.id.iv_3) ImageView iv_3;

    @BindView(R.id.iv_close_1) ImageView iv_close_1;
    @BindView(R.id.iv_close_2) ImageView iv_close_2;
    @BindView(R.id.iv_close_3) ImageView iv_close_3;

    private int type = 1;//报修类别：1.室内报修 2.室外报修
    private ImageView mCurrImg,mCurrClose;int mCurrIndex=1;
    private HashMap<Integer,String> imgHash = new HashMap<>();
    public BasePopupView popupView;
    @Override
    protected int getLayout() {
        return R.layout.activity_maintain;
    }

    @Override
    protected void initEventAndData() {
        iv_close_1.setVisibility(View.GONE);
        iv_close_2.setVisibility(View.GONE);
        iv_close_3.setVisibility(View.GONE);
        popupView = new XPopup.Builder(this).dismissOnTouchOutside(false).asLoading("请稍后");
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        title.setText("业主报修");

        String loignjson = SPUtils.getInstance().getString(SP_LOGIN_BEAN);
        LoginBean bean = JsonUtil.jsonToBean(loignjson, LoginBean.class);
        if (bean != null) {
            edit_name.setText(bean.getName());
            edit_phone.setText(bean.getPhone());
            edit_house.setText(bean.getAddress());
        }
    }

    @OnClick({R.id.btn_commit
            ,R.id.iv_close_1,R.id.iv_1
            ,R.id.iv_close_2,R.id.iv_2
            ,R.id.iv_close_3,R.id.iv_3
            ,R.id.rl_type})
    public void doClick(View view){
        switch (view.getId()){
            case R.id.btn_commit:
                commit();
                break;
            case R.id.iv_1:
                mCurrImg = iv_1;
                mCurrIndex =1;
                mCurrClose = iv_close_1;
                selectPic();
                break;
            case R.id.iv_2:
                mCurrImg = iv_2;
                mCurrIndex =2;
                mCurrClose = iv_close_2;
                selectPic();
                break;
            case R.id.iv_3:
                mCurrImg = iv_3;
                mCurrIndex =3;
                mCurrClose = iv_close_3;
                selectPic();
                break;
            case R.id.rl_type:
                new XPopup.Builder(MaintainActivity.this)
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{"室内报修", "室外报修"},
                                new int[]{},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        type = position+1;
                                        tv_bxtype.setText(type==1?"室内报修":"室外报修");
                                    }
                                })
                        .show();
                break;
            case R.id.iv_close_1:
                clearPic();
                break;
            case R.id.iv_close_2:
                clearPic();
                break;
            case R.id.iv_close_3:
                clearPic();
                break;
        }
    }

    private void clearPic(){
        mCurrImg.setImageResource(R.mipmap.camera);
        imgHash.remove(mCurrIndex);
        mCurrClose.setVisibility(View.GONE);
    }

    private void commit(){
        String desc1 = edt_desc.getText().toString();
        String name2 = edit_name.getText().toString();
        String phone = edit_phone.getText().toString();
        String house = edit_house.getText().toString();

        if (TextUtils.isEmpty(desc1)){
            edt_desc.requestFocus();
            edt_desc.setError("请填写报修描述");
            return;
        }

        String imglist ="";
        for (Map.Entry<Integer, String> entry: imgHash.entrySet()) {
            String value = entry.getValue();
            imglist += (value+",");
        }
        if(imglist.length() > 1){
            imglist = imglist.substring(0,imglist.length()-1);
        }
        LogUtil.d("imglist="+imglist);
        if (TextUtils.isEmpty(imglist)){
            ToastUtil.error("请上传图片");
            return;
        }

        if (TextUtils.isEmpty(name2)){
            edit_name.requestFocus();
            edit_name.setError("请填写联系人");
            return;
        }

        if (TextUtils.isEmpty(phone)){
            edit_phone.requestFocus();
            edit_phone.setError("请填写联系电话");
            return;
        }

        if (TextUtils.isEmpty(house)){
            edit_house.requestFocus();
            edit_house.setError("请填写楼宇号");
            return;
        }

        Api.getApiService().addBx(SPUtils.getCustomId(),type+"",desc1,imglist,name2,phone,house).enqueue(new ZyCallBack() {
            @Override
            public void doSuccess() {
                ToastUtil.success("您已提交成功");
                MaintainActivity.this.finish();
            }
        });
    }

    //上传图片
    private void uploadPic(final String filepath, final String base64){
        Map<String, String> params = new HashMap<>();
        params.put("img", base64);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), base64);
        Api.getApiService().addImg(requestBody).enqueue(new ZyCallBack<UploadImgBean>(popupView) {
            @Override
            public void doSuccess() {
                UploadImgBean bean = mData;
                mCurrClose.setVisibility(View.VISIBLE);
                imgHash.put(mCurrIndex,bean.getImgUrl());
                GlideUtils.load(MaintainActivity.this,mCurrImg,filepath);
                LogUtil.d("图片上传成功,路径="+bean.getImgUrl());
            }
        });
    }

    //选择图片
    private void selectPic(){
        new XPopup.Builder(MaintainActivity.this)
                .asCustom(new SelectHeadPopup(MaintainActivity.this, new SelectHeadPopup.SelectPhoto() {
                    @Override
                    public void take() {
                        //拍一张图片
                        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                        Uri imageUri = Uri.fromFile(file);

                        TakePhoto takePhoto2 = getTakePhoto();
                        takePhoto2.onEnableCompress(null, false);
                        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
                        builder.setWithOwnGallery(true);
                        takePhoto2.setTakePhotoOptions(builder.create());

                        takePhoto2.onPickFromCapture(imageUri);
                    }

                    @Override
                    public void select() {
                        //选一张图片
                        TakePhoto takePhoto = getTakePhoto();
                        takePhoto.onEnableCompress(null, false);
                        takePhoto.onPickFromGallery();
                    }
                }))
                .show();
    }


    /****************************************************
     *      一下为图片处理部分
     ****************************************************/
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public void takeSuccess(TResult result) {
        final String path = result.getImage().getOriginalPath();
        if (TextUtils.isEmpty(path)) {
            ToastUtil.shortShow("图片路径为空");
            return;
        }
        LogUtil.e("path = "+path);
        popupView.show();
        compress(path);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        ToastUtil.shortShow("操作失败 " + msg);
    }

    @Override
    public void takeCancel() {

    }

    //图片压缩
    private void compress(final String path){
        String cunlj = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
        LogUtil.d("存储目录:"+cunlj);
        Luban.with(this)
                .load(path)
                .ignoreBy(20)
                .setTargetDir(cunlj)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        LogUtil.d("压缩成功,文件路径:"+file.getAbsolutePath());
                        uploadPic(file.getAbsolutePath(), MyUtil.encodeBase64File2(file.getAbsolutePath()));
                    }

                    @Override
                    public void onError(Throwable e) {
                        popupView.dismiss();
                        ToastUtil.error("压缩失败");
                    }
                }).launch();
    }
}
